<template>
  <div class="mod-category">
    <el-tree
      ref="treeRef"
      :data="menus"
      show-checkbox
      node-key="catId"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="[]"
      :props="defaultProps"
      @node-expand="nodeExpand"
      @node-collapse="nodeCollapse"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="appendIfNotLeafNode(node)" type="text" size="mini" @click="() => append(data)">Append</el-button>
          <el-button v-if="removeIfThereAreNoChildren(node)" type="text" size="mini" @click="() => remove(node, data)">Delete</el-button>
        </span>
      </span>
    </el-tree>

    <category-dialog
      :dialog-form-visible="dialogFormVisible"
      @closeDialog="closeDialog"
    />

    <single-upload />
  </div>
</template>

<script>
import categoryDialog from '@/views/modules/product/categoryDialog'
import singleUpload from '@//components/upload/singleUpload'

export default {
  name: 'category',
  components: {
    categoryDialog,
    singleUpload
  },
  data () {
    return {
      defaultExpandedKeys: [],
      menus: [],
      defaultProps: {
        children: 'categoryEntityList',
        label: 'name'
      },
      dialogFormVisible: false
    }
  },
  activated () {
    this.getCategoryTree()
  },
  methods: {
    /** 获取产品三级菜单树 */
    async getCategoryTree () {
      let loading = this.mallUtils.getLoading()
      let categoryTreeResponse = await this.$mallHttp.get('/product/category/list/tree')
      console.log('categoryTreeResponse === ', categoryTreeResponse)
      loading.close()
      let isResponseNormally = this.mallUtils.isResponseNormally(categoryTreeResponse)
      this.menus = isResponseNormally ? categoryTreeResponse.data.data : []
    },
    // 新增节点
    append (data) {
      console.log('新增节点 ===== ')
      console.log('data === ', data)
      // const newChild = { id: id++, label: 'testtest', children: [] }
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // data.children.push(newChild)
    },
    // 移除节点
    remove (currentNode, currentData) {
      console.log('移除节点 ===== ')
      console.log('node === ', currentNode)
      console.log('data === ', currentData)
      console.log('this.defaultExpandedKeys = ', this.defaultExpandedKeys)

      const ids = [currentData.catId]
      const names = [currentData.name]
      this.$confirm(`确定对['${ids.join(',')}-${names.join(',')}']进行['删除']操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.deleteCategoryBatch(ids)
      }).catch(() => {})
    },
    /** 批量删除三级菜单 */
    async deleteCategoryBatch (catIds) {
      let loading = this.mallUtils.getLoading()
      let deleteResponse = await this.$mallHttp.post('/product/category/delete', catIds)
      console.log('deleteResponse === ', deleteResponse)
      loading.close()
      let isResponseNormally = this.mallUtils.isResponseNormally(deleteResponse)
      if (isResponseNormally) {
        this.$message.success('删除成功！')
        await this.getCategoryTree()
      }
    },
    appendIfNotLeafNode (node) {
      return !node.isLeaf
    },
    removeIfThereAreNoChildren (node) {
      return node.childNodes.length === 0
    },
    /** 节点被展开时触发的事件 */
    nodeExpand (data, node, vueComponent) {
      console.log('nodeExpand === ')
      console.log(data, node, vueComponent)
      this.getSubExpandedKeys(data, node).forEach(expandedKey => {
        this.defaultExpandedKeys.push(expandedKey)
      })
      console.log('this.defaultExpandedKeys === ', this.defaultExpandedKeys)
    },
    /** 节点被关闭时触发的事件 */
    nodeCollapse (data, node, vueComponent) {
      console.log('nodeCollapse === ')
      console.log(data, node, vueComponent)
      this.getSubExpandedKeys(data, node).forEach(expandedKey => {
        this.defaultExpandedKeys = this.defaultExpandedKeys.filter(item => item !== expandedKey)
      })
      console.log('this.defaultExpandedKeys === ', this.defaultExpandedKeys)
    },
    /** 获取当前节点下所有展开的子节点的业务ID数组 */
    getSubExpandedKeys (data, node) {
      const subExpandedKeys = [data.catId]
      this.recursionExpandedSubNodes(node, subExpandedKeys)
      return subExpandedKeys
    },
    /** 递归当前节点下所有展开的子节点，并将展开的子节点业务ID放入数组中(subExpandedKeys) */
    recursionExpandedSubNodes (node, subExpandedKeys) {
      if (node.childNodes.length > 0) {
        node.childNodes.filter(childNode => childNode.expanded).forEach(childNode => {
          subExpandedKeys.push(childNode.data.catId)
          this.recursionExpandedSubNodes(childNode, subExpandedKeys)
        })
      }
    },
    /** 打开弹框 */
    openDialog () {
      this.dialogFormVisible = true
    },
    /** 关闭弹框 */
    closeDialog () {
      this.dialogFormVisible = false
    }
  }
}
</script>

<style scoped>

</style>
